package org.example.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @author 莫磊
 * @date 2025/8/8
 * @description
 */
@Controller
// 使用这个注解，表示value中的属性是存放到session域对象中
@SessionAttributes(value = {"httpSession"})
public class DomainController {

	// @RequestMapping("/")
	public String testRequest(HttpServletRequest request) {
		// 测试域对象
		request.setAttribute("testRequestScope", "测试request作用域");
		return "success";
	}

	/**
	 * map
	 * modelMap
	 * model这三个底层都是用了BindingAwareModelMap类进行封装
	 * @param model
	 * @return
	 */
	@RequestMapping("/testModel")
	public String testRequest(Model model) {
		// 测试域对象
		model.addAttribute("testRequestScopeForModel", "通过Model接口测试request作用域");
		return "success";
	}

	@RequestMapping("/testMap")
	public String testRequest(Map<String, Object> map) {
		// 测试域对象
		map.put("testRequestScopeForMap", "通过Map接口测试request作用域");
		return "success";
	}

	@RequestMapping("/testModelMap")
	public String testRequest(ModelMap model) {
		// 测试域对象
		model.addAttribute("testRequestScopeForModelMap", "通过ModelMap接口测试request作用域");
		return "success";
	}

	@RequestMapping("/testModelAndView")
	public ModelAndView testModelAndView() {
		ModelAndView mv = new ModelAndView();
		mv.addObject("testModelAndView", "通过ModelAndView测试request作用域");
		mv.setViewName("success");
		// 测试域对象
		return mv;
	}

	@RequestMapping("/testSession")
	public String testSession(HttpSession session) {
		session.setAttribute("testSessionScope", session.getAttribute("testSessionScope") + "  测试session作用域");
		return "success";
	}

	@RequestMapping("/testAnSession")
	public String testSession(Model model) {
		model.addAttribute("httpSession", "通过注解设置session属性");
		return "success";
	}

	@RequestMapping("/testApplication")
	public String testApplication(HttpServletRequest request) {
		request.getServletContext().setAttribute("testApplicationScope", "测试应用作用域");
		return "success";
	}

}
